<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- AdThrive Head Tag Manual -->
    <script data-no-optimize="1" data-cfasync="false">
      (function (w, d) {
        w.adthrive = w.adthrive || {};
        w.adthrive.cmd = w.adthrive.cmd || [];
        w.adthrive.plugin = "adthrive-ads-manual";
        w.adthrive.host = "ads.adthrive.com";
        var s = d.createElement("script");
        s.async = true;
        s.referrerpolicy = "no-referrer-when-downgrade";
        s.src =
          "https://" +
          w.adthrive.host +
          "/sites/643436a4e6d20859e40a446b/ads.min.js?referrer=" +
          w.encodeURIComponent(w.location.href) +
          "&cb=" +
          (Math.floor(Math.random() * 100) + 1);
        var n = d.getElementsByTagName("script")[0];
        n.parentNode.insertBefore(s, n);
      })(window, document);
    </script>
    <!-- End of AdThrive Head Tag -->

    <!-- Global site tag (gtag.js) - Google Analytics -->

    <script
      async
      src="https://www.googletagmanager.com/gtag/js?id=UA-79254642-6"
    ></script>

    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag() {
        dataLayer.push(arguments);
      }
      gtag("js", new Date());

      gtag("config", "UA-79254642-6");
    </script>

    <meta charset="utf-8" />
    <title>Boxplot &#124; the D3 Graph Gallery</title>

    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta
      name="description"
      content="How to build a boxplot with Javascript and D3.js: from the most basic example to highly customized examples."
    />
    <meta
      name="keywords"
      content="Data,Dataviz,Datavisualization,Javascript,D3,D3.js,boxplot"
    />
    <meta name="author" content="Yan Holtz" />
    <link rel="icon" href="img/logo/D3_single_small.png" />

    <meta property="og:title" content="Boxplot &#124; the D3 Graph Gallery" />
    <meta property="og:image" content="img/overview_RGG.png" />
    <meta
      property="og:description"
      content="How to build a boxplot with Javascript and D3.js: from the most basic example to highly customized examples."
    />

    <!-- Bootstrap core CSS -->
    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet" />

    <!-- Custom fonts for this template -->
    <link
      href="vendor/font-awesome/css/font-awesome.min.css"
      rel="stylesheet"
      type="text/css"
    />
    <link
      href="https://fonts.googleapis.com/css?family=Montserrat:400,700"
      rel="stylesheet"
      type="text/css"
    />
    <link
      href="https://fonts.googleapis.com/css?family=Kaushan+Script"
      rel="stylesheet"
      type="text/css"
    />
    <link
      href="https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic"
      rel="stylesheet"
      type="text/css"
    />
    <link
      href="https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700"
      rel="stylesheet"
      type="text/css"
    />

    <!-- Custom styles for this template -->
    <link href="css/agency.css" rel="stylesheet" />

    <!-- JQUERY -->
    <script src="vendor/jquery/jquery.min.js"></script>

    <!-- d3.v4 and Plugin for color scale -->
    <script src="js/d3.v4.js"></script>
    <script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
  </head>

  <body id="page-top">
    <!-- THIS ALLOWS TO INSERT THE MENU THAT IS STORED IN A MENU.HTML FILE-->
    <nav class="navbar navbar-expand-lg fixed-top" id="mainNav"></nav>
    <script>
      $(function () {
        $("#mainNav").load("html_chunk/menu.html");
      });
    </script>

    <!-- THIS ALLOWS TO INSERT THE MODAL OF THE MENU THAT IS STORED IN A MENU_MODAL.HTML FILE-->
    <div id="modal_menu_insertion"></div>
    <script>
      $(function () {
        $("#modal_menu_insertion").load("html_chunk/menu_modal.html");
      });
    </script>

    <!-- Header -->
    <header class="masthead" style="padding-top: 150px; padding-bottom: 80px">
      <div class="textlanding">
        <h1>Boxplot</h1>
        <hr class="short_hr" />
        <br />
        <ul class="list-inline social-buttons">
          <li class="list-inline-item">
            <a href="https://twitter.com/R_Graph_Gallery">
              <i class="fa fa-twitter"></i>
            </a>
          </li>
          <li class="list-inline-item social-buttons">
            <a href="https://github.com/holtzy">
              <i class="fa fa-github" style="color: white"></i>
            </a>
          </li>
          <li class="list-inline-item social-buttons">
            <a href="https://www.linkedin.com/in/yan-holtz-2477534a/">
              <i class="fa fa-linkedin"></i>
            </a>
          </li>
          <li class="list-inline-item social-buttons">
            <a href="https://www.yan-holtz.com">
              <i class="fa fa-home"></i>
            </a>
          </li>
        </ul>
        <br /><br />
        <p style="max-width: 700px; margin: auto">
          This is the
          <a href="https://www.data-to-viz.com/caveat/boxplot.html">boxplot</a>
          section of the gallery. If you want to know more about this kind of
          chart, visit
          <a href="https://www.data-to-viz.com/caveat/boxplot.html"
            >data-to-viz.com</a
          >. If you're looking for a simple way to implement it in d3.js, pick
          an example below.
        </p>
      </div>
    </header>

    <!-- THIS ALLOWS TO INSERT THE ADVERTISEMENT BANNER THAT IS STORED IN A BANNER.HTML FILE-->
    <div id="position_for_images"></div>
    <script>
      $(function () {
        $("#position_for_images").load("html_chunk/images.html");
      });
    </script>

    <!-- ======================== PORTFOLIO SECTION ============================ --><!-- Images must be 480 x 480, resize them with ./script_reformat_img.sh output_name.png -->
    <section class="bg" id="portfolio" style="padding-top: 10px">
      <div class="container">
        <div class="mySeryTitle">Step by step</div>
        <hr />
        <div id="portfolio-items" class="row">
          <div class="col-md-4 col-sm-6 portfolio-item">
            <a class="portfolio-link" href="graph/boxplot_basic.html">
              <div class="portfolio-hover">
                <div class="portfolio-hover-content">
                  <p>Most basic</p>
                  <hr />
                  <p class="explanation_portfolio">
                    The most basic boxplot you can do in d3.js. Keeping only the
                    core code. Starts with an array of data.
                  </p>
                </div>
              </div>
              <img class="img-fluid" src="img/graph/boxplot_basic.png" alt="" />
            </a>
          </div>
          <div class="col-md-4 col-sm-6 portfolio-item">
            <a class="portfolio-link" href="graph/boxplot_several_groups.html">
              <div class="portfolio-hover">
                <div class="portfolio-hover-content">
                  <p>With several group</p>
                  <hr />
                  <p class="explanation_portfolio">
                    A boxplot with several groups. It extends the technique used
                    on the previous chart. The tricky part is to computed
                    summary statistics for each group.
                  </p>
                </div>
              </div>
              <img
                class="img-fluid"
                src="img/graph/boxplot_several_groups.png"
                alt=""
              />
            </a>
          </div>
          <div class="col-md-4 col-sm-6 portfolio-item">
            <a
              class="portfolio-link"
              href="graph/boxplot_show_individual_points.html"
            >
              <div class="portfolio-hover">
                <div class="portfolio-hover-content">
                  <p>Show individual data points</p>
                  <hr />
                  <p class="explanation_portfolio">
                    The major downside of boxplot is that it hides the
                    underlying data points. It is a good practice to show them
                    using jitter. Learn how with this example.
                  </p>
                </div>
              </div>
              <img
                class="img-fluid"
                src="img/graph/boxplot_show_individual_points.png"
                alt=""
              />
            </a>
          </div>
        </div>

        <br /><br />
        <div class="mySeryTitle">Template</div>
        <hr />
        <p>
          Here is the template I'm starting with when in need for a boxplot in
          my work. See the code
          <a href="graph/boxplot_horizontal.html">here</a>.
        </p>
        <div class="row">
          <div class="col-lg-12">
            <center><div id="boxplot_template"></div></center>
          </div>
        </div>

        <br /><br />
        <div class="mySeryTitle">Related blocks</div>
        <hr />
      </div>
    </section>

    <!-- ======================================================================= -->

    <!-- ============================ JAVASCRIPT BOXPLOT TEMPLATE ============================ -->

    <!-- Tooltip style -->
    <style>
      .tooltip {
        background-color: black;
        border: none;
        border-radius: 5px;
        padding: 15px;
        min-width: 200px;
        text-align: left;
        color: white;
      }

      svg {
        border: 1px solid #e8e8e8;
        border-radius: 6px;
      }
    </style>

    <script>
      // set the dimensions and margins of the graph
      var margin = { top: 10, right: 30, bottom: 50, left: 70 },
        width = 760 - margin.left - margin.right,
        height = 600 - margin.top - margin.bottom;

      // append the svg object to the body of the page
      var svg = d3
        .select("#boxplot_template")
        .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

      // Read the data and compute summary statistics for each specie
      d3.csv(
        "https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/iris.csv",
        function (data) {
          // Compute quartiles, median, inter quantile range min and max --> these info are then used to draw the box.
          var sumstat = d3
            .nest() // nest function allows to group the calculation per level of a factor
            .key(function (d) {
              return d.Species;
            })
            .rollup(function (d) {
              q1 = d3.quantile(
                d
                  .map(function (g) {
                    return g.Sepal_Length;
                  })
                  .sort(d3.ascending),
                0.25
              );
              median = d3.quantile(
                d
                  .map(function (g) {
                    return g.Sepal_Length;
                  })
                  .sort(d3.ascending),
                0.5
              );
              q3 = d3.quantile(
                d
                  .map(function (g) {
                    return g.Sepal_Length;
                  })
                  .sort(d3.ascending),
                0.75
              );
              interQuantileRange = q3 - q1;
              min = q1 - 1.5 * interQuantileRange;
              max = q3 + 1.5 * interQuantileRange;
              return {
                q1: q1,
                median: median,
                q3: q3,
                interQuantileRange: interQuantileRange,
                min: min,
                max: max,
              };
            })
            .entries(data);

          // Show the Y scale
          var y = d3
            .scaleBand()
            .range([height, 0])
            .domain(["setosa", "versicolor", "virginica"])
            .padding(0.4);
          svg
            .append("g")
            .call(d3.axisLeft(y).tickSize(0))
            .select(".domain")
            .remove();

          // Show the X scale
          var x = d3.scaleLinear().domain([4, 8]).range([0, width]);
          svg
            .append("g")
            .attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x).ticks(5))
            .select(".domain")
            .remove();

          // Color scale
          var myColor = d3
            .scaleSequential()
            .interpolator(d3.interpolateInferno)
            .domain([4, 8]);

          // Add X axis label:
          svg
            .append("text")
            .attr("text-anchor", "end")
            .attr("x", width)
            .attr("y", height + margin.top + 30)
            .text("Sepal Length");

          // Show the main vertical line
          svg
            .selectAll("vertLines")
            .data(sumstat)
            .enter()
            .append("line")
            .attr("x1", function (d) {
              return x(d.value.min);
            })
            .attr("x2", function (d) {
              return x(d.value.max);
            })
            .attr("y1", function (d) {
              return y(d.key) + y.bandwidth() / 2;
            })
            .attr("y2", function (d) {
              return y(d.key) + y.bandwidth() / 2;
            })
            .attr("stroke", "black")
            .style("width", 40);

          // rectangle for the main box
          svg
            .selectAll("boxes")
            .data(sumstat)
            .enter()
            .append("rect")
            .attr("x", function (d) {
              return x(d.value.q1);
            }) // console.log(x(d.value.q1)) ;
            .attr("width", function (d) {
              return x(d.value.q3) - x(d.value.q1);
            }) //console.log(x(d.value.q3)-x(d.value.q1))
            .attr("y", function (d) {
              return y(d.key);
            })
            .attr("height", y.bandwidth())
            .attr("stroke", "black")
            .style("fill", "#69b3a2")
            .style("opacity", 0.3);

          // Show the median
          svg
            .selectAll("medianLines")
            .data(sumstat)
            .enter()
            .append("line")
            .attr("y1", function (d) {
              return y(d.key) + y.bandwidth() / 2;
            })
            .attr("y2", function (d) {
              return y(d.key) + y.bandwidth() / 2;
            })
            .attr("x1", function (d) {
              return x(d.value.median);
            })
            .attr("x2", function (d) {
              return x(d.value.median);
            })
            .attr("stroke", "black")
            .style("width", 80);

          // create a tooltip
          var tooltip = d3
            .select("#boxplot_template")
            .append("div")
            .style("opacity", 0)
            .attr("class", "tooltip")
            .style("font-size", "16px");
          // Three function that change the tooltip when user hover / move / leave a cell
          var mouseover = function (d) {
            tooltip.transition().duration(200).style("opacity", 1);
            tooltip
              .html(
                "<span style='color:grey'>Sepal length: </span>" +
                  d.Sepal_Length
              ) // + d.Prior_disorder + "<br>" + "HR: " +  d.HR)
              .style("left", d3.mouse(this)[0] + 30 + "px")
              .style("top", d3.mouse(this)[1] + 30 + "px");
          };
          var mousemove = function (d) {
            tooltip
              .style("left", d3.mouse(this)[0] + 30 + "px")
              .style("top", d3.mouse(this)[1] + 30 + "px");
          };
          var mouseleave = function (d) {
            tooltip.transition().duration(200).style("opacity", 0);
          };

          // Add individual points with jitter
          var jitterWidth = 60;
          svg
            .selectAll("indPoints")
            .data(data)
            .enter()
            .append("circle")
            .attr("cx", function (d) {
              return x(d.Sepal_Length);
            })
            .attr("cy", function (d) {
              return (
                y(d.Species) +
                y.bandwidth() / 2 -
                jitterWidth / 2 +
                Math.random() * jitterWidth
              );
            })
            .attr("r", 6)
            .style("fill", function (d) {
              return myColor(+d.Sepal_Length);
            })
            .attr("stroke", "black")
            .on("mouseover", mouseover)
            .on("mousemove", mousemove)
            .on("mouseleave", mouseleave);
        }
      );
    </script>

    <!-- ============================ RELATED SECTION ============================ -->
    <section
      class="bg-light"
      id="portfolio_landing"
      style="padding-top: 30px; padding-bottom: 30px"
    >
      <div class="container">
        <p class="mySeryTitle">Related chart types</p>
        <hr />
        <div class="row">
          <div class="col-md-2 col-sm-4 portfolio-item">
            <a class="portfolio-link" href="violin.html">
              <div class="portfolio-hover">
                <div class="portfolio-hover-content">
                  <i class="fa fa-plus fa-3x"></i>
                </div>
              </div>
              <img class="img-fluid" src="img/section/Violin150.png" alt="" />
            </a>
            <div class="captionPortfolio">Violin</div>
          </div>
          <div class="col-md-2 col-sm-4 portfolio-item">
            <a class="portfolio-link" href="density.html">
              <div class="portfolio-hover">
                <div class="portfolio-hover-content">
                  <i class="fa fa-plus fa-3x"></i>
                </div>
              </div>
              <img class="img-fluid" src="img/section/Density150.png" alt="" />
            </a>
            <div class="captionPortfolio">Density</div>
          </div>
          <div class="col-md-2 col-sm-4 portfolio-item">
            <a class="portfolio-link" href="histogram.html">
              <div class="portfolio-hover">
                <div class="portfolio-hover-content">
                  <i class="fa fa-plus fa-3x"></i>
                </div>
              </div>
              <img
                class="img-fluid"
                src="img/section/Histogram150.png"
                alt=""
              />
            </a>
            <div class="captionPortfolio">Histogram</div>
          </div>
          <div class="col-md-2 col-sm-4 portfolio-item">
            <a class="portfolio-link" href="boxplot.html">
              <div class="portfolio-hover">
                <div class="portfolio-hover-content">
                  <i class="fa fa-plus fa-3x"></i>
                </div>
              </div>
              <img class="img-fluid" src="img/section/Box1150.png" alt="" />
            </a>
            <div class="captionPortfolio">Boxplot</div>
          </div>
          <div class="col-md-2 col-sm-4 portfolio-item">
            <a class="portfolio-link" href="ridgeline.html">
              <div class="portfolio-hover">
                <div class="portfolio-hover-content">
                  <i class="fa fa-plus fa-3x"></i>
                </div>
              </div>
              <img class="img-fluid" src="img/section/Joyplot150.png" alt="" />
            </a>
            <div class="captionPortfolio">Ridgeline</div>
          </div>
        </div>
      </div>
    </section>

    <!-- ============================ CONTACT SECTION ============================ -->

    <!-- ANCHOR -->
    <a name="contactanchor"></a>

    <section id="contact" class="bg" style="background-color: white"></section>

    <!-- THIS ALLOWS TO INSERT THE CONTACT CHUNK THAT IS STORED IN A CONTACT.HTML FILE-->
    <script>
      $(function () {
        $("#contact").load("html_chunk/contact.html");
      });
    </script>

    <!-- ============================ FOOTER SECTION ============================ -->
    <footer class="bg-light" id="myFooter"></footer>

    <!-- Start Added by AdThrive -->
    <script
      type="text/javascript"
      async
      src="https://btloader.com/tag?o=5698917485248512&upapi=true&domain=d3-graph-gallery.com"
    ></script>
    <script>
      !(function () {
        "use strict";
        var e;
        (e = document),
          (function () {
            var t, n;
            function r() {
              var t = e.createElement("script");
              (t.src =
                "https://cafemedia-com.videoplayerhub.com/galleryplayer.js"),
                e.head.appendChild(t);
            }
            function a() {
              var t = e.cookie.match("(^|[^;]+)\s*__adblocker\s*=\s*([^;]+)");
              return t && t.pop();
            }
            function c() {
              clearInterval(n);
            }
            return {
              init: function () {
                var e;
                "true" === (t = a())
                  ? r()
                  : ((e = 0),
                    (n = setInterval(function () {
                      (100 !== e && "false" !== t) || c(),
                        "true" === t && (r(), c()),
                        (t = a()),
                        e++;
                    }, 50)));
              },
            };
          })().init();
      })();
    </script>
    <!-- End Added by AdThrive -->

    <!-- THIS ALLOWS TO INSERT THE FOOTER THAT IS STORED IN A FOOTER.HTML FILE-->
    <script>
      $(function () {
        $("#myFooter").load("html_chunk/footer.html");
      });
    </script>

    <!-- ============================ -->

    <!-- =============== JAVASCRIPT SECTION =============== -->

    <!-- Bootstrap core JavaScript -->
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Plugin JavaScript -->
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- Custom scripts for this template -->
    <script src="js/agency.min.js"></script>

    <!--============================== -->
  </body>
</html>
